package org.elanfox.intellicommunity.intellicommunityadmin.base.security;


import lombok.Setter;
import org.elanfox.intellicommunity.biz.service.core.auth.SystemService;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;


/**
 * @author allan
 * @date 10/11/2017
 */
@Setter
public class SmAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {
    private PasswordEncoder passwordEncoder;

    private SystemService systemService;

    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authenticationToken) throws AuthenticationException {

        if (!userDetails.isEnabled()) {
            throw new LockedException("账户已锁定");
        }

        //密码校验
        String presentedPassword = userDetails.getPassword();
        if (!passwordEncoder.matches((String) authenticationToken.getCredentials(), presentedPassword)) {
            throw new BadCredentialsException(messages.getMessage(
                    "AbstractUserDetailsAuthenticationProvider.badCredentials",
                    "Bad credentials"));
        }
    }

    @Override
    protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken) throws AuthenticationException {
        UserDetails userDetails;
        try {
            userDetails = systemService.loadUserByUsername(username);
        } catch (Exception e) {
            throw new UsernameNotFoundException("帐号不存在", e);
        }

        if (userDetails == null) {
            throw new UsernameNotFoundException("帐号不存在");
        }
        return userDetails;
    }
}
